package org.xtext.runtime.teleoreactive;

import org.xtext.runtime.formula.Predicate;
import org.xtext.runtime.interpreter.ASTRAClass;
import org.xtext.runtime.interpreter.Agent;
import org.xtext.runtime.util.Bindings;
import org.xtext.runtime.util.Unifier;

public class TRFunctionCall implements ITRAction {
	private Predicate function;
	private ASTRAClass clazz;
	
	public TRFunctionCall(ASTRAClass clazz, Predicate function) {
		this.clazz = clazz;
		this.function = function;
	}
	
	public String toString() {
		return function.toString();
	}
	
	@Override
	public boolean handle(Agent agent) {
		TRFunction fn = clazz.getFunction(function);
		if (fn != null) {
			Bindings bindings = Unifier.unify(function, fn.identifier());
			if (bindings != null) {
				return fn.apply(bindings).invoke(agent);
			}
		}
		return false;
	}

	@Override
	public TRFunctionCall apply(Bindings bindings) {
		return new TRFunctionCall(clazz, function.copy().apply(bindings));
	}

	@Override
	public ITRAction copy() {
		return new TRFunctionCall(clazz, function.copy());
	}
}
